package com.xb.p22_handlerprocessbar;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public void log(String str){
        Log.i("main:",str);
    }


    TextView textView=null;
    ProgressBar progressBar=null;
    Handler update_handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            log("Handler："+msg.arg1);
            //更新进度条
            progressBar.setProgress(msg.arg1);
            update_handler.post(updateProgressBar);
            if(msg.arg1>100){
                log("remove:");
                removeCallbacks(updateProgressBar);
            }
        }
    };

    //进度条线程
    Runnable updateProgressBar = new Runnable() {
        int i=0;
        @Override
        public void run() {
            log("run："+i);
            i=i+10;
            Message msg=update_handler.obtainMessage();
            msg.arg1=i;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            update_handler.sendMessage(msg);//将数据发送给Handler
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_start).setOnClickListener(this);
        findViewById(R.id.btn_stop).setOnClickListener(this);
        progressBar=findViewById(R.id.progress_horizontal);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_start:
                update_handler.post(updateProgressBar);
                break;
            case R.id.btn_stop:
                update_handler.removeCallbacks(updateProgressBar);
                break;
        }
    }
}